import wx from 'wx';
import { ajax } from 'm7-ajax';

const link = location.href.split('#')[0];
function json (api, path, query = '') {
  return new Promise((resolve, reject) => {
    ajax({
      url: `${api}/${path}?${query}`,
      onSuccess (data) {
        resolve(data);
      },
      onError (error) {
        reject(error);
      }
    });
  });
}
function signaturewx () {
  const url = encodeURIComponent(location.href.split('#')[0]);
  return json('https://minisite-c.snailvr.com', 'weixin/getsign.php', `url=${url}`).then((data) => {
    wx.config({
      debug: false,
      appId: data.appId,
      timestamp: data.timestamp,
      nonceStr: data.nonceStr,
      signature: data.signature,
      jsApiList: [
        'checkJsApi',
        'chooseImage',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone'
      ]
    });
  });
}
function configwx (config) {
  wx.ready(() => {
    wx.onMenuShareTimeline({
      title: config.title,
      link: link,
      imgUrl: config.imgUrl
    });
    wx.onMenuShareAppMessage({
      title: config.title,
      desc: config.desc,
      link: link,
      imgUrl: config.imgUrl,
      type: config.type,
      dataUrl: config.dataUrl
    });
    wx.onMenuShareQQ({
      title: config.title,
      desc: config.desc,
      link: link,
      imgUrl: config.imgUrl
    });
    wx.onMenuShareWeibo({
      title: config.title,
      desc: config.desc,
      link: link,
      imgUrl: config.imgUrl
    });
    wx.onMenuShareQZone({
      title: config.title,
      desc: config.desc,
      link: link,
      imgUrl: config.imgUrl
    });
  });
}
export function sharewx (shareMsg) {
  signaturewx().then((data) => {
    configwx(shareMsg);
  });
}

export function configChooseImage ({ count, sizeType, sourceType, callback }) {
  wx.ready(() => {
    wx.chooseImage({
      count,
      sizeType,
      sourceType,
      success: callback,
      fail: (res) => {
        console.log(JSON.String(res));
      }
    });
  });
}
